package org.ms.mtx.example.service;

import org.apache.commons.lang3.StringUtils;
import org.ms.mtx.core.annotation.Transactional;
import org.ms.mtx.core.context.TransactionContextHolder;
import org.ms.mtx.example.service.cannel.StockCancelService;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 库存服务
 *
 * @author lry
 */
@Service
public class StockService {

    /**
     * 模拟库存
     */
    public static AtomicInteger stock = new AtomicInteger(100);

    @Transactional(cancelClass = StockCancelService.class)
    public Boolean stock(Integer number, String exceptionMock) {
        if (StringUtils.isNotBlank(exceptionMock) && exceptionMock.equals(Thread.currentThread().getStackTrace()[1].getMethodName())) {
            throw new RuntimeException("模拟异常:" + Thread.currentThread().getStackTrace()[1].getMethodName());
        }

        Integer stockNum;
        if ((stockNum = stock.get() - number) <= 0) {
            throw new RuntimeException("库存不足");
        } else {
            // 模拟传输中间参数
            TransactionContextHolder.addAttribute("stockNum", stockNum);
            System.out.println("校验库存:" + stock.get());
        }

        return true;
    }

    public Boolean stockConfirm(Integer number, String exceptionMock) {
        if (StringUtils.isNotBlank(exceptionMock) && exceptionMock.equals(Thread.currentThread().getStackTrace()[1].getMethodName())) {
            throw new RuntimeException("模拟异常:" + Thread.currentThread().getStackTrace()[1].getMethodName());
        }

        Integer stockNum = TransactionContextHolder.getAttribute("stockNum");
        System.out.println("模拟获取中间参数:" + stockNum);
        System.out.println("减少库存:库存从[" + stock.get() + "]减少为[" + stock.addAndGet(-number) + "]");
        return true;
    }

}
